import React, { useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';
import {Card, List, WhiteSpace} from 'antd-mobile';
import { getDetail } from '../../services/List';
import {Brief} from "antd-mobile/es/list/ListItem";
import useUserInfo from '../../models/userInfo';
import {logout} from "../../services/Login";

const Index = () => {
  const history = useHistory();
  const [state, setState] = useState([]);
  const { userInfo, saveUserInfo } = useUserInfo();
  useEffect(() => {
    const fetch = async () => {
      const res = await getDetail();
      const data = res.data.map((item) => {
        const temp = item.expiration.split('T');

        return {
          time: `${temp[0]} ${temp[1].split('+')[0]}`,
          name: item.name,
          id: item.id,
        };
      });

      setState(data);
    };

    fetch();
  }, []);

  const onLogout = async () => {
    await logout();
    saveUserInfo(null, null, null);
    history.push('/login');
  };

  return (
    <div>
      <div style={{display: 'flex', justifyContent: 'space-between'}}>
        <div>当前用户：{userInfo.nk}</div>
        <div onClick={() => onLogout()}>登出</div>
      </div>
      <List renderHeader='作业'>
      {state.map((item) => (
        <>
          <List.Item arrow="horizontal" onClick={() => history.push(`/handle?id=${item.id}`)}>
            {item.name}
            <Brief>{item.time}</Brief>
          </List.Item>
          <WhiteSpace />
        </>
      ))}
      </List>
    </div>
  );
};

export default Index;
